<?php
class db_messages
{
	/*
	* Messages Database Class for Twicha
	*	Version 3.0
	*
	*/
	function __construct()
	{
		Global $mySql, $lib;
		$this->mySql = $mySql;
		$this->lib = $lib;	
		
	}
	public function getMessages($opts)
	{	
		// Get Defined Variables
		if(EMPTY($opts))
		{
			$opts = array();
		}
		$sql = Array();
		
		// Count the Number of Feeds
		$count = 0;
		foreach( $opts["prefs"] as $key => $value )
		{
			if($value)
			{
				$count++;
			}
			else
			{
			}
		}
		if($count == 0)
		{
			return false;
		}
		
		
		// Set Up Database Fields
		$dbfields = array(
							"msg.Tbl_ID",
							"msg.User_ID",
							"msg.Message",
							"msg.OrgAuth",
							"msg.Active",
							"msg.Time_TS",
							"msg.Rating",
							"vote.Vote_TS as Vote",
							"follow.Follow_ID",
							"follow.Action",
							"replies.Msg_ID as Reply_ID");
		$dbjoins = array(
							"replies" => "msg.Tbl_ID = replies.Msg_ID AND replies.User_ID = %d",
							"vote" => "msg.Tbl_ID = vote.Msg_ID AND vote.User_ID = %d",
							"follow" => "msg.User_ID = follow.Follow_ID AND follow.User_ID = %d",
						);
		
		// Where Options
		$sql["Where"][] = db_messages::returnFeedStatement($opts["prefs"]);
		if(!EMPTY($opts["time"]["time1"]))
		{
			$sql["Where"][] = " AND Time_TS > " . mysql_real_escape_string($opts["time"]["time1"]);
		}
		if(!EMPTY($opts["time"]["time2"]))
		{
			$sql["Where"][] = " AND Time_TS < " . mysql_real_escape_string($opts["time"]["time2"]);
		}
		// Sort Options
		if($opts["sort"] == "Rating")
		{
			$sql["Sort"][] = "Rating DESC";
		}
		$cleanarray = db_messages::stripBadFields($sql);
		
		
		// Start the SQL Creation
		$sql = "SELECT ";
		$count = 1;
		foreach($dbfields as $value)
		{
			if($count == 1)
			{
				$sql .= " \n" . $value;
			}
			else
			{
				$sql .= ", \n".$value;
			}
			$count++;
		}
		$sql .= "\nFROM messages msg \n";
		foreach($dbjoins as $table => $arg)
		{
			$temp = "LEFT JOIN " . $table ." ON " . $arg . "\n";
			$sql .= @sprintf($temp, $this->Login['login']['id']);
		}
		$sql .= "WHERE ";
		if(!EMPTY($cleanarray["Where"]))
		{
			foreach($cleanarray["Where"] as $key => $arg)
			{
				$sql .= $arg . "\n";
			}
		}
		$sql .= "ORDER BY ";
		if(!EMPTY($cleanarray["Sort"]))
		{
			foreach($cleanarray["Sort"] as $key => $arg)
			{
				$sql .= $arg . ", ";
			}
		}
		$sql .= "Time_TS Desc";
		$sql .= " \nLIMIT 0,12";
		$result = $this->mySql->makeQuery($sql);
		$num = 0;		
		// Data Sorting
		if(isset($result))
		{
			while($temp = mysqli_fetch_array($result))
			{
				$num++;
				$data[$num]['Tbl_ID'] = $temp['Tbl_ID'];
				$data[$num]['User_ID'] = $temp['User_ID'];
				$data[$num]['Message'] = $temp['Message'];
				$data[$num]['OrgAuth'] = $temp['OrgAuth'];
				$data[$num]['Active'] = $temp['Active'];
				$data[$num]['Time_TS'] = $temp['Time_TS'];
				$data[$num]['Rating'] = $temp['Rating'];
				$data[$num]['Vote_TS'] = $temp['Vote'];
				$data[$num]['Reply_ID'] = $temp['Reply_ID'];
				$data[$num]['Follow_ID'] = $temp['Follow_ID'];
				$data[$num]['Action'] = $temp['Action'];
			}
			@$this->lastRequest['data'] = $data;
			@$this->lastRequest['length'] = $num;
			@$this->lastRequest['query'] = $sql;
			return @$data;
		}
		else
		{
			return false;
		}
	}
	/*
	* Builds the Messages MySQL Statement
	* $array = array of options
	*/
	public function buildMySQL($array)
	{
		
	}
	public function stripBadFields($array)
	{
		$validfields = array (
								"Sort" => 1,
								"Where" => 1,
								);
		return lib::cleanArray($validfields, $array);
	}
	function insertMessage($form)
	{
		$userid = $form[id];
		$message = $form[message];
		$data = $this->findReplies($message);
		$orgauth = $this->lib->findUserNamebyID($userid);
		$ipaddress = $_SERVER["REMOTE_ADDR"];
		if(!EMPTY($userid) && !EMPTY($message) && !EMPTY($orgauth))
		{
			$sql = "INSERT INTO messages (User_ID, Message, OrgAuth, IP_Addr) VALUES ('%s','%s','%s','%s')";
			$query = sprintf($sql,
	            mysql_real_escape_string($userid),
	            mysql_real_escape_string($message),
				mysql_real_escape_string($orgauth),
				mysql_real_escape_string($ipaddress),
				mysql_real_escape_string($reply));
			$this->mySql->makeQuery($query);
		}
		else
		{
			return false;
		}
		$id = mysql_insert_id();
		if(!EMPTY($data[users]))
		{
			$this->insertReplyList($data[users], $id);
		}
		if(!$this->mySql->listErrors())
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}
	function returnFeedStatement($opts)
	{
		$count = 0;
		foreach( $opts as $key => $value )
		{
			if($value)
			{
				$count++;
				$feeds[] = $key;
			}
			else
			{
			}
		}
		$block = " follow.Action != -1 ";
		$sql = "";
		if($count == 0)
		{
			return false;
		}
		if($count == 1)
		{
			if($opts["reply"] == true)
			{
				$block = "";
			}
			return  "\n " . $block . db_messages::getStatement($feeds[0], 1) ;
		}
		
		// Everyone Statement
		if($opts["everyone"] == true)
		{
			return $block . "\n OR " . db_messages::getStatement("everyone") ;
		}
		
		// Home Statement
		if($opts["home"] == true)
		{
			$sql .= "\n AND " . db_messages::getStatement("home");
		}
		
		// Reply Statement
		if($opts["reply"] == true)
		{
			$sql .= " OR" . db_messages::getStatement("reply");
		}
		return $block . $sql ;
	}
	function getStatement($feed, $args="")
	{
		if(EMPTY($args))
		{
			if($feed == "everyone")
			{
				return " follow.Action IS NULL";
			}
			if($feed == "home")
			{
				return " follow.Action IS NOT NULL";
			}
			elseif($feed == "reply")
			{
				return " replies.User_ID IS NOT NULL";
			}
		}
		else
		{
			if($feed == "everyone")
			{
				return " OR follow.Action IS NULL";
			}
			if($feed == "home")
			{
				return "AND follow.Action IS NOT NULL";
			}
			elseif($feed == "reply")
			{
				return " replies.User_ID IS NOT NULL";
			}
		}
	}
	function insertReplyList($data, $msgid)
	{
		$sql = $this->buildNameList($data);
		$result = $this->mySql->makeQuery($sql);
		$idList = Array();
		while($temp = mysql_fetch_array($result))
		{	
			$idList[] = $temp[Tbl_ID];
		}
		print_r($idList);
		foreach($idList as $key => $foreachid)
		{
			$sql = "INSERT INTO replies (Msg_ID, User_ID) VALUES (%d,%d)";
			$query = sprintf($sql,
	            mysql_real_escape_string($msgid),
	            mysql_real_escape_string($foreachid));
			$this->mySql->makeQuery($query);
		}
	}
	function buildNameList($name)
	{
		$sql = "SELECT *"; 
        $sql .= " FROM users"; 
		foreach($name as $key => $data)
		{
		  if (!EMPTY($data)) 
           { 
                $search[] = sprintf(" Username='%s' ", mysql_real_escape_string($data)); 
           } 
		 }
           if (TRUE != empty($search)) 
           { 
                foreach ($search as $key => $string) 
                { 
                     if (0 === $key) 
                     { 
                          $sql .= " WHERE"; 
                     } 
                     if (0 < $key) 
                     { 
                          $sql .= " OR"; 
                     } 
                     $sql .= " ".$string; 
                } 
           }
		   else
		   {
			unset($sql);
		   }
		echo $sql;
	   return $sql;
		
	}
	function findReplies($data)
	{
		$data = $data . " ";
		$temp = explode("@", $data);
		foreach ($temp as $key => $message)
		{
			if($key != 0)
			{
				$string = substr($message, 0, strpos($message," "));
				$return[users][] = substr($string, 0, strlen($data));
			}
		}
		print_r($return[users]);
		$return[message] = $data;
		return $return;
	}
}